<template>
  <div>
    <h2>外出销假</h2>

    <el-table :data="tableData" row-key="outingId">
      <el-table-column prop="Name" label="老人姓名" />
      <el-table-column prop="reason" label="外出事由" />
      <el-table-column prop="expectReturn" label="预计返回" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 0 ? 'warning' : row.status === 2 ? 'success' : 'info'">
            {{ ['已申请','已出门','已返回','已撤销'][row.status] }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 仅“已出门”状态才显示销假按钮 -->
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button v-if="row.status === 1"
                     type="primary" size="small"
                     @click="openCheckIn(row)">
            销假
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 销假弹窗 -->
    <el-dialog v-model="show" title="外出销假">
      <el-form :model="form" label-width="120px">
        <el-form-item label="实际返回时间">
          <el-date-picker v-model="form.actualReturn"
                          type="datetime"
                          placeholder="选填，默认当前时间" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="submitCheckIn">确认销假</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getOutingPage, checkInOuting } from '@/api/outing'

const tableData = ref([])
const show = ref(false)
const form = ref({})

/* 根据登录角色过滤数据 */
const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
const elderId = userInfo.role === 'family' ? userInfo.elderId : null

const load = async () => {
  const res = await getOutingPage({current: 1, size: 50, elderId})
  tableData.value = res.data.records
}

const openCheckIn = (row) => {
  form.value = {outingId: row.outingId, actualReturn: ''}
  show.value = true
}

const submitCheckIn = async () => {
  await checkInOuting(form.value)   // 调用 PUT /outing/check-in
  show.value = false
  load()        // 刷新列表
}

onMounted(load)
</script>